#ifndef EARTHWIDGET_H
#define EARTHWIDGET_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QMatrix4x4>
#include <QVector3D>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QVector>
#include <QImage>
#include <QOpenGLTexture>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTime>
#include <QTimer>
#include <QVector2D>

struct VertexData {
    QVector3D position;
    QVector3D normal;
    QVector2D texCoord;
};

struct Star {
    QVector3D position;
    float brightness;
    float flickerSpeed;
};

struct Light {
    QVector3D position;
    QVector3D color;
    float intensity;
};

// OBJ模型数据结构
struct ModelData {
    QVector<VertexData> vertices;
    QVector<GLuint> indices;
    GLuint texture;
    bool textureLoaded;
    QVector3D position;
    QVector3D scale;
    float rotation;
};

class EarthWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    enum TextureType {
        BlueMarbleHD,     // 2048x1024
        BlueMarble4K,     // 4096x2048
        NightLights,      // 夜景
        Topography,       // 地形图
        CloudCover        // 云层
    };
    Q_ENUM(TextureType)

    explicit EarthWidget(QWidget *parent = nullptr);
    ~EarthWidget();

    void addMarker(float latitude, float longitude, const QVector3D& color = QVector3D(1.0f, 0.0f, 0.0f));
    bool loadEarthTexture(const QString& imagePath);
    void downloadNASATexture(const QString& urlString);
    void downloadDefaultNASATexture(TextureType type = BlueMarbleHD);
    void clearMarkers();

    // 模型管理函数
    bool loadModel(const QString& objPath, const QString& texturePath = "");
    void addModelAtLocation(float latitude, float longitude, const QString& modelName,
                            const QVector3D& scale = QVector3D(0.1f, 0.1f, 0.1f));
    void clearModels();

    // 路径管理函数
    QString getApplicationPath();
    QString getTexturesPath();
    QString getCachePath();
    bool loadLocalTexture(const QString& relativePath);
    bool saveDownloadedTexture(const QImage& image, const QString& filename);
    QString getCachedTexturePath(const QString& filename);
    bool loadCachedTexture(const QString& filename);

public slots:
    void onTextureDownloaded(QNetworkReply* reply);
    void updateAnimation();

signals:
    void textureLoaded(bool success);
    void markerAdded(float latitude, float longitude);
    void modelAdded(float latitude, float longitude, const QString& modelName);

protected:
    void initializeGL() override;
    void resizeGL(int w, int h) override;
    void paintGL() override;

    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;

private:
    void createSphereGeometry();
    void createMarkerGeometry();
    void createStarsGeometry();
    void setupMultipleLights();
    void calculateModelNormals(QVector<VertexData>& vertices);
    void drawModelGeometry(const ModelData& model);
    bool loadOBJModel(const QString& path, ModelData& model);
    bool loadModelTexture(const QString& path, ModelData& model);
    QVector3D screenToWorldCoordinates(int x, int y);
    QVector3D cartesianToGeographic(const QVector3D& point);
    QVector3D geographicToCartesian(float latitude, float longitude);
    void updateCamera();
    GLuint loadTexture(const QImage& image);
    void createDefaultTexture();
    void initializePaths();
    void drawModels();

    // 着色器程序
    QOpenGLShaderProgram *m_earthProgram;
    QOpenGLShaderProgram *m_markerProgram;
    QOpenGLShaderProgram *m_starProgram;
    QOpenGLShaderProgram *m_modelProgram;

    // 缓冲区对象
    QOpenGLBuffer m_earthVbo;
    QOpenGLBuffer m_earthIbo;
    QOpenGLVertexArrayObject m_earthVao;

    QOpenGLBuffer m_markerVbo;
    QOpenGLBuffer m_markerIbo;
    QOpenGLVertexArrayObject m_markerVao;

    QOpenGLBuffer m_starVbo;
    QOpenGLVertexArrayObject m_starVao;

    // 纹理
    GLuint m_earthTexture;
    bool m_textureLoaded;

    // 网络管理
    QNetworkAccessManager* m_networkManager;

    // 动画计时器
    QTimer* m_animationTimer;
    QTime m_time;

    // 几何数据
    QVector<VertexData> m_earthVertices;
    QVector<GLuint> m_earthIndices;
    QVector<VertexData> m_markerVertices;
    QVector<GLuint> m_markerIndices;
    QVector<Star> m_stars;

    // 变换矩阵
    QMatrix4x4 m_projection;
    QMatrix4x4 m_view;
    QMatrix4x4 m_model;

    // 相机参数
    float m_distance;
    float m_rotationX;
    float m_rotationY;

    // 光照系统
    QVector<Light> m_lights;
    float m_ambientStrength;

    // 鼠标交互
    QPoint m_lastMousePos;
    bool m_isRotating;

    // 标记点
    struct Marker {
        QVector3D position;
        QVector3D color;
        QMatrix4x4 modelMatrix;
        QString label;
    };
    QVector<Marker> m_markers;

    // 3D模型
    QMap<QString, ModelData> m_loadedModels;  // 已加载的模型
    struct PlacedModel {
        QString modelName;
        QVector3D position;
        QVector3D scale;
        float rotation;
        QMatrix4x4 modelMatrix;
    };
    QVector<PlacedModel> m_placedModels;

    // 球体参数
    int m_stacks;
    int m_slices;
    float m_radius;

    // 星星参数
    int m_starCount;
};

#endif // EARTHWIDGET_H
